package normalsys.demo.base.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import tk.mybatis.spring.mapper.MapperScannerConfigurer;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * Project Name: ms
 * File Name: MybatisConfig
 * Package Name: normalsys.demo.base.config
 * Date: 2018/6/25  11:14
 * Copyright (c) 2018, tianyul All Rights Reserved.
 */
@Configuration
public class MybatisConfig {
    public MybatisConfig() {
    }

    @Bean(
            name = {"sqlSessionFactory"}
    )
    public SqlSessionFactory sqlSessionFactoryBean(@Qualifier("dataSource") DataSource dataSource) {
        try {
            ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
            SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
            bean.setDataSource(dataSource);
            bean.setTypeAliasesPackage(this.getTypeAliasesPackage());
            if (null != this.getMapperLocations() && !"".equals(this.getMapperLocations())) {
                bean.setMapperLocations(resourcePatternResolver.getResources(this.getMapperLocations()));
            }

            org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
            configuration.setUseColumnLabel(true);
            configuration.setMapUnderscoreToCamelCase(true);
            bean.setConfiguration(configuration);
            bean.setFailFast(true);
            return bean.getObject();
        } catch (Exception var5) {
            throw new RuntimeException("sqlSessionFactory of mybatis init fail!", var5);
        }
    }

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage(this.getBasePackage());
        Properties properties = new Properties();
        properties.setProperty("value", "mappers=mapper.MsMapper");
        mapperScannerConfigurer.setProperties(properties);
        return mapperScannerConfigurer;
    }

    protected String getTypeAliasesPackage() {
        return "normalsys.demo.entity";
    }

    protected String getMapperLocations() {
        return "";
    }

    protected String getBasePackage() {
        return "normalsys.demo.dao";
    }
}
